// pythonlauncher.cpp
#include "pythonlauncher.h"
#include <QDebug>
#include <QUrl>

PythonLauncher::PythonLauncher(QObject *parent) : QObject(parent)
{
    m_pythonProcess = new QProcess();

    // 关联信号与槽（处理输出和结束事件）
    connect(m_pythonProcess, &QProcess::readyReadStandardOutput,
            this, &PythonLauncher::onReadyReadStandardOutput);
    connect(m_pythonProcess, &QProcess::readyReadStandardError,
            this, &PythonLauncher::onReadyReadStandardError);
    connect(m_pythonProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            this, &PythonLauncher::pythonFinished);
}

// 启动 Python 脚本
void PythonLauncher::startPythonScript(const QString &scriptPath)
{
    if (m_pythonProcess->state() == QProcess::Running) {
        emit pythonError("Python 进程已在运行中");
        return;
    }

    // 将 file:// URI 转换为文件系统路径
    QString filePath = QUrl(scriptPath).toLocalFile();

    // 调试输出，确认路径是否正确
    qDebug() << "转换后的文件路径:" << filePath;

    // 启动 Python 进程
    m_pythonProcess->start("python", QStringList() << filePath<<" "<<"1");

    if (!m_pythonProcess->waitForStarted()) {
        emit pythonError("启动 Python 失败：" + m_pythonProcess->errorString());
    }
}

// 处理 Python 标准输出
void PythonLauncher::onReadyReadStandardOutput()
{
    QString output = m_pythonProcess->readAllStandardOutput();
    emit pythonOutput(output); // 发送到 QML
}

// 处理 Python 错误输出
void PythonLauncher::onReadyReadStandardError()
{
    QString error = m_pythonProcess->readAllStandardError();
    emit pythonError(error); // 发送到 QML
}
